<!--
 * @Date: 2024-07-25 15:56:09
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2025-03-05 09:42:04
 * @Description: 字段选择弹窗
-->
<template>
  <vxe-modal
    :="dialogAttrs"
    @hide="handleClose"
    @close="handleClose"
    v-model="dialogStore.visible"
  >
    <VfDataTable
      ref="tableRef"
      :="tableAttrs"
      @radioChange="radioChange"
    >
      <template #toolbar_left>
        <div class="field-tag">
          <span>当前选择：</span>
          <span>{{ tableStore.selectRow?.value || '暂无'  }}</span>
        </div>
      </template>
      <template #toolbar_right>
        <div style="display: flex">
          <el-input
            size="default"
            style="margin-right: 12px; width: 180px;"
            v-model="tableParams.filterName"
            placeholder="请输入字典名称或字典值"
            @keyup.enter="searchMethod"
          />
          <el-button size="default" type="primary" @click="searchMethod">查询</el-button>
          <el-button size="default" @click="resetMethod">重置</el-button>
        </div>
      </template>
    </VfDataTable>
    <template #footer>
      <el-button size="default" type="primary" @click="handleConfirm">确定</el-button>
      <el-button size="default" @click="handleClose">取消</el-button>
    </template>
  </vxe-modal>
</template>

<script setup name="DictSelectDialog">
import { VfMessage } from '@/utils/vf-utils'
import { VfDataTable } from '@/components/vf-table';
import { ref, reactive, nextTick, inject } from 'vue';

import XEUtils from 'xe-utils';
import { baseAttrs } from '@/components/dialogs/cfg/base-cofig.js'
import { SelectDictDataType } from '@/base/pojo/SelectDataType.js'
import { getBaseDataDictTableList } from '@/api/api-setting';

const emits = defineEmits(['close', 'confirm']);
const props = defineProps({
  // 字典名称
  dictName: { type: String },
  // 字典类型
  dictType: { type: String },
  // 枚举数据池
  enumsDataPools: { type: [Object, Array] },
});

const axiosConfig = inject('axiosConfig');


// ----- 弹窗相关
const dialogAttrs = reactive({
  ...baseAttrs,
  title: '选择字典名称',
})
// 弹窗数据集
const dialogStore = reactive({
  visible: false,
})

// 打开弹窗
const handleOpen = config => {
  if (!props.dictType) {
    VfMessage.warning('请选择字典类型！');
    return;
  }
  dialogStore.visible = true;
  loadTableData();
};
const handleClose = () => {
  dialogStore.visible = false;
  emits('close');
};
const handleConfirm = () => {
  const currentRow = tableRef.value.getRadioRecord();
  if (currentRow) {
    dialogStore.visible = false;
    emits('confirm', currentRow);
  } else {
    VfMessage.warning('请选择一条记录，进行操作！');
  }
};

// ----- 表格相关
const tableRef = ref();
const tableAttrs = reactive({
  data: [],
  loading: false,
  keyField: 'value',
  boxConfig: { mode: 'radio' },
  pagerConfig: false,
  radioConfig: { trigger: 'row', highlight: true },
  radioCacelBtn: true,
  toolbarConfig: { refresh: false },
  columns: [
    { field: 'label', title: '字典名称' },
    { field: 'value', title: '字典值' },
  ]
})
const tableStore = reactive({
  selectRow: {},
  cacheData: []
})
const tableParams = reactive({
  filterName: ''
})

const searchMethod = () => {
  const filterName = XEUtils.toValueString(tableParams.filterName).trim().toLowerCase();
  if (filterName) {
    const filterRE = new RegExp(filterName, 'gi');
    const searchProps = ['label', 'value'];
    const rest = tableAttrs.data.filter(item =>
      searchProps.some(
        key => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1,
      ),
    );
    const list = rest.map(row => {
      const item = Object.assign({}, row);
      searchProps.forEach(key => {
        item[key] = XEUtils.toValueString(item[key]).replace(filterRE, match => `${match}`);
      });
      return item;
    });
    tableAttrs.data = list;
  } else {
    tableAttrs.data = XEUtils.clone(tableStore.cacheData, true);
  }
};
const resetMethod = () => {
  tableParams.filterName = '';
  tableAttrs.data = XEUtils.clone(tableStore.cacheData, true);
};
const reqTableData = () => {
  const { dictType, enumsDataPools } = props;
  return new Promise(resolve => {
    if (SelectDictDataType.ENUMS.equals(dictType)) {
      const enumsData = Object.values(enumsDataPools);
      tableStore.cacheData = XEUtils.clone(enumsData, true);
      resolve(XEUtils.clone(enumsData, true));
    } else if (SelectDictDataType.BASE.equals(dictType)) {
      getBaseDataDictTableList(axiosConfig.request).then(res => {
        const { code, data, msg } = res;
        if (code === 200) {
          tableStore.cacheData = XEUtils.clone(data, true);
          resolve(data);
        } else {
          resolve([]);
        }
      });
    } else {
      resolve([]);
    }
  });
};
const loadTableData = async () => {
  tableAttrs.data = [];
  tableStore.cacheData = [];
  tableStore.selectRow = {};
  tableParams.filterName = '';
  tableAttrs.loading = true
  const result = await reqTableData();
  tableAttrs.loading = false
  tableAttrs.data = result;
  setCurrentRow();
};
const setCurrentRow = () => {
  const { dictName } = props
  if (!dictName) return
  nextTick(() => {
    const selectRow = tableAttrs.data.find(item => item.value == dictName)
    if (!selectRow) return 
    tableStore.selectRow = selectRow
    tableRef.value.setRadioRow(selectRow)
    setTimeout(() => { tableRef.value.scrollToRow(selectRow) }, 300);
  });
};
/**
 * 单选选中时触发
 *
 * @param values { row }
 */
const radioChange = (values) => {
  tableStore.selectRow = values ? values.row : ''
}

// ---- 方法暴露
defineExpose({
  handleOpen,
});
</script>

<style lang="scss" scoped>
.field-tag {
  color: #fff;
  background-color: #3eaf7c;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 5px;
  font-weight: 600;
}
</style>
